import cv from 'opencv.js'

class ImageMatcher {
  constructor() {
    this.isReady = false
    this.initializeOpenCV()
  }

  initializeOpenCV() {
    return new Promise((resolve) => {
      if (cv.getBuildInformation) {
        this.isReady = true
        resolve()
      } else {
        cv.onRuntimeInitialized = () => {
          this.isReady = true
          resolve()
        }
      }
    })
  }

  async waitForReady() {
    if (!this.isReady) {
      await this.initializeOpenCV()
    }
  }

  /**
   * 在源图像中查找模板图像
   * @param {string} sourceImagePath - 源图像路径
   * @param {string} templateImagePath - 模板图像路径
   * @returns {Promise<{x: number, y: number, width: number, height: number}>}
   */
  async locateTemplate(sourceImagePath, templateImagePath) {
    await this.waitForReady()

    return new Promise((resolve, reject) => {
      try {
        // 加载图像
        const sourceImage = new Image()
        const templateImage = new Image()

        sourceImage.onload = () => {
          templateImage.onload = () => {
            try {
              const result = this.matchImages(sourceImage, templateImage)
              resolve(result)
            } catch (error) {
              reject(error)
            }
          }
          templateImage.onerror = () => reject(new Error('模板图像加载失败'))
          templateImage.src = templateImagePath
        }
        
        sourceImage.onerror = () => reject(new Error('源图像加载失败'))
        sourceImage.src = sourceImagePath
      } catch (error) {
        reject(error)
      }
    })
  }

  matchImages(sourceImg, templateImg) {
    // 创建临时 canvas
    const sourceCanvas = document.createElement('canvas')
    const templateCanvas = document.createElement('canvas')
    
    sourceCanvas.width = sourceImg.width
    sourceCanvas.height = sourceImg.height
    templateCanvas.width = templateImg.width
    templateCanvas.height = templateImg.height

    const sourceCtx = sourceCanvas.getContext('2d')
    const templateCtx = templateCanvas.getContext('2d')

    sourceCtx.drawImage(sourceImg, 0, 0)
    templateCtx.drawImage(templateImg, 0, 0)

    // 转换为 OpenCV 矩阵
    const sourceMat = cv.imread(sourceCanvas)
    const templateMat = cv.imread(templateCanvas)

    // 转换为灰度图
    const sourceGray = new cv.Mat()
    const templateGray = new cv.Mat()
    cv.cvtColor(sourceMat, sourceGray, cv.COLOR_RGBA2GRAY)
    cv.cvtColor(templateMat, templateGray, cv.COLOR_RGBA2GRAY)

    // 模板匹配
    const result = new cv.Mat()
    cv.matchTemplate(sourceGray, templateGray, result, cv.TM_CCOEFF_NORMED)

    // 寻找最佳匹配位置
    const minMax = cv.minMaxLoc(result)
    const maxPoint = minMax.maxLoc

    const position = {
      x: maxPoint.x,
      y: maxPoint.y,
      width: templateGray.cols,
      height: templateGray.rows
    }

    // 清理内存
    sourceMat.delete()
    templateMat.delete()
    sourceGray.delete()
    templateGray.delete()
    result.delete()

    return position
  }
}

export default new ImageMatcher()